package com.poisonh.unifiedauth.utils;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * 图片操作工具包
 *
 * @version 1.0
 */
public class ImageUtils {

    /**
     * 获取圆形图片的方法
     *
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
        try {
            Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(outBitmap);
            final int color = 0xff424242;
            final Paint paint = new Paint();
            int round = 0;
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            if (width > height) {
                round = height;
            } else {
                round = width;
            }
            final Rect rect = new Rect(0, 0, round, round);
            final RectF rectF = new RectF(rect);
            final float roundPX = round / 2;
            paint.setAntiAlias(true);
            canvas.drawARGB(0, 0, 0, 0);
            paint.setColor(color);
            canvas.drawRoundRect(rectF, roundPX, roundPX, paint);
            paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
            canvas.drawBitmap(bitmap, rect, rect, paint);
            return outBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }


    /**
     * bitmap转Base64
     *
     * @param bit
     * @return
     */

    public static String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 根据uri获取文件路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getPathFromUri(Context context, Uri uri) {
        String path = "";
        if (uri != null && context != null) {
            String[] pro = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(uri, pro, null, null, null);
            if (cursor == null) {
                path = uri.getPath();
            } else if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                path = cursor.getString(column_index);
                cursor.close();
            }
        }
        return path;
    }

    /**
     * 获取Bitmap
     *
     * @param context
     * @param uri
     * @return
     */
    public static Bitmap getBitmap(Context context, Uri uri) {
        Bitmap bitmap = null;
        try {
            if (uri != null) {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, options);
                int width = options.outWidth;
                int height = options.outHeight;
                options.inJustDecodeBounds = false;
                DisplayMetrics metrics = new DisplayMetrics();
                ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics);
                int screenWidth = metrics.widthPixels / 4;
                int screenHeight = metrics.heightPixels;
                int scaleSize = 0;
                scaleSize = width / screenWidth;
                if (scaleSize < height / screenHeight) {
                    scaleSize = height / screenHeight;
                }
                if (scaleSize < 1) {
                    scaleSize = 1;
                }
                options.inSampleSize = scaleSize;
                bitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, options);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 保存bitmap并返回保存路径
     *
     * @param context
     * @param name    图片名称,带后缀
     * @param bitmap
     * @return 保存bitmap的文件Uri
     */
    public static Uri saveBitmap(Context context, String name, Bitmap bitmap) {
        return saveBitmap(context, name, "bitmap", bitmap);
    }

    public static Uri saveBitmap(Context context, String name, String pathName, Bitmap bitmap) {
        Uri uri = null;
        File file = context.getExternalFilesDir(pathName);
        file = new File(file, name);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
            uri = Uri.fromFile(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uri;
    }

    /**
     * 压缩保存图片文件
     * 原文件不会删除
     * 仅支持JPG格式
     *
     * @param context
     * @param filePath
     * @return 压缩后的文件路径
     */
    public static String scaleSaveBitmap(Context context, String filePath) {
        return scaleSaveBitmap(context, filePath, false);
    }

    /**
     * 获取压缩图片路径
     *
     * @param context
     * @return
     */
    public static String getScaleSavePath(Context context) {
        String saveFilePath = UriUtil.getBitmapFilePath(context, "head.jpg");
        return saveFilePath;
    }


    /**
     * 压缩保存图片文件
     * 原文件不会删除
     * 仅支持JPG格式
     *
     * @param context
     * @param filePath
     * @param isWaterMark 是否添加时间水印
     * @return 压缩后的文件路径
     */
    public static String scaleSaveBitmap(Context context, String filePath, boolean isWaterMark) {
        return scaleSaveBitmap(context, filePath, isWaterMark, 0);
    }

    /**
     * 压缩保存图片文件
     * 原文件不会删除
     * 仅支持JPG格式
     *
     * @param context
     * @param filePath
     * @param isWaterMark    是否添加时间水印
     * @param waterMarkColor 水印颜色
     * @return 压缩后的文件路径
     */
    public static String scaleSaveBitmap(Context context, String filePath, boolean isWaterMark, int waterMarkColor) {
        File file = new File(filePath);
        String saveFilePath = "";
        if (file.exists()) {
            saveFilePath = getScaleSavePath(context);
            scaleSaveBitmap(filePath, saveFilePath, isWaterMark, waterMarkColor);
        }
        return saveFilePath;

    }

    /**
     * 压缩保存图片文件
     * 原文件不会删除
     * 仅支持JPG格式
     *
     * @param filePath     原文件
     * @param saveFilePath 结果文件
     * @module 通用
     */
    public static void scaleSaveBitmap(String filePath, String saveFilePath) {
        scaleSaveBitmap(filePath, saveFilePath, false);
    }

    /**
     * 压缩保存图片文件
     * 原文件不会删除
     * 仅支持JPG格式
     *
     * @param filePath     原文件
     * @param saveFilePath 结果文件
     * @param isWaterMark  是否添加时间水印
     * @module 通用
     */
    public static void scaleSaveBitmap(String filePath, String saveFilePath, boolean isWaterMark) {
        scaleSaveBitmap(filePath, saveFilePath, isWaterMark, 0);
    }

    /**
     * 压缩保存图片文件
     * 原文件不会删除
     * 仅支持JPG格式
     *
     * @param filePath       原文件
     * @param saveFilePath   结果文件
     * @param isWaterMark    是否添加时间水印
     * @param waterMarkColor 水印颜色
     * @module 通用
     */
    public static void scaleSaveBitmap(String filePath, String saveFilePath, boolean isWaterMark, int waterMarkColor) {
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
            int width = 720;
            int height = 1280;
            int outWidth = options.outWidth;
            int outHeight = options.outHeight;
            int scale;
            int scaleW = outWidth / width;
            int scaleH = outHeight / height;
            if (scaleH > scaleW) {
                scale = scaleH;
            } else {
                scale = scaleW;
            }
            if (scale < 1) {
                scale = 1;
            }
            options.inSampleSize = scale;
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(filePath, options);
            if (isWaterMark) {
                bitmap = setTimeWaterMark(bitmap, waterMarkColor);
            }
            File newFile = new File(saveFilePath);
            FileOutputStream fileOutputStream = new FileOutputStream(newFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int quality = 100;
            int length = 0;
            do {
                bos.reset();
                bitmap.compress(Bitmap.CompressFormat.WEBP, quality, bos);
                length = bos.toByteArray().length;
                quality -= 10;
            } while (length > 50 * 1024 && quality > 0);
            bos.writeTo(fileOutputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取圆角Bitmap
     *
     * @param bitmap  源图
     * @param radius  圆角半径
     * @param corners 指定角，不指定为圆角矩形
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int radius, ImageCorner... corners) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Rect completeRect = new Rect(0, 0, width, height);
        Rect leftTopRect = new Rect(0, 0, radius, radius);
        Rect leftBottomRect = new Rect(0, height - radius, radius, height);
        Rect rightTopRect = new Rect(width - radius, 0, width, radius);
        Rect rightBottomRect = new Rect(width - radius, height - radius, width, height);
        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Paint paint = new Paint();
        paint.setAntiAlias(true);

        canvas.drawRect(completeRect, paint);

        if (corners.length == 0) {
            corners = new ImageCorner[]{ImageCorner.LEFT_TOP, ImageCorner.LEFT_BOTTOM, ImageCorner.RIGHT_TOP, ImageCorner.RIGHT_BOTTOM};
        }

        for (ImageCorner corner : corners) {
            switch (corner) {
                case LEFT_TOP:
                    paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
                    canvas.drawRect(leftTopRect, paint);
                    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
                    canvas.drawCircle(radius, radius, radius, paint);
                    break;
                case LEFT_BOTTOM:
                    paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
                    canvas.drawRect(leftBottomRect, paint);
                    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
                    canvas.drawCircle(radius, height - radius, radius, paint);
                    break;
                case RIGHT_TOP:
                    paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
                    canvas.drawRect(rightTopRect, paint);
                    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
                    canvas.drawCircle(width - radius, radius, radius, paint);
                    break;
                case RIGHT_BOTTOM:
                    paint.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
                    canvas.drawRect(rightBottomRect, paint);
                    paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OVER));
                    canvas.drawCircle(width - radius, height - radius, radius, paint);
                    break;
                default:
                    break;
            }
        }
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, 0, 0, paint);
        bitmap.recycle();
        return output;
    }

    /**
     * 获取纯色的Bitmap
     *
     * @param width
     * @param height
     * @param color
     * @return
     */
    public static Bitmap getColorBitmap(int width, int height, int color) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
        Canvas canvasTemp = new Canvas(bitmap);
        canvasTemp.drawColor(color);
        return bitmap;
    }

    /**
     * 将Drawable转化为Bitmap
     *
     * @param drawable
     * @return
     */
    public static Bitmap drawableToBitmap(Drawable drawable) {
        int width = drawable.getIntrinsicWidth();
        int height = drawable.getIntrinsicHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, height, drawable
                .getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
                : Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, width, height);
        drawable.draw(canvas);
        return bitmap;

    }

    /**
     * 设置时间水印
     *
     * @param res
     * @param waterMarkColor 水印颜色，默认白色
     * @return
     */
    public static Bitmap setTimeWaterMark(Bitmap res, int waterMarkColor) {
        Bitmap bitmap = Bitmap.createBitmap(res.getWidth(), res.getHeight(), Config.ARGB_8888);
        //初始化画布 绘制的图像到bitmap上
        Canvas canvas = new Canvas(bitmap);
        //建立画笔
        Paint photoPaint = new Paint();
        //获取跟清晰的图像采样
        photoPaint.setDither(true);
        canvas.drawBitmap(res, 0, 0, photoPaint);
        if (res != null && !res.isRecycled()) {
            res.recycle();
            res = null;
            System.gc();
        }

        //设置画笔
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        //字体大小
        textPaint.setTextSize(50f);
        //采用默认的宽度
        textPaint.setTypeface(Typeface.DEFAULT);
        if (waterMarkColor == 0) {
            waterMarkColor = Color.WHITE;
        }
        //采用的颜色
        textPaint.setColor(waterMarkColor);

        // 时间水印
        String mark = formateDate("yyyy.MM.dd HH:mm:ss");
        float textWidth = textPaint.measureText(mark);
        canvas.drawText(mark, bitmap.getWidth() - textWidth - 10, bitmap.getHeight() - 26, textPaint);
        return bitmap;
    }

    /**
     * 设置时间水印
     *
     * @param res
     */
    public static Bitmap setTimeWaterMark(Bitmap res) {
        Bitmap bitmap = Bitmap.createBitmap(res.getWidth(), res.getHeight(), Config.ARGB_8888);
        //初始化画布 绘制的图像到bitmap上
        Canvas canvas = new Canvas(bitmap);
        //建立画笔
        Paint photoPaint = new Paint();
        //获取跟清晰的图像采样
        photoPaint.setDither(true);
        canvas.drawBitmap(res, 0, 0, photoPaint);
        if (res != null && !res.isRecycled()) {
            res.recycle();
            res = null;
            System.gc();
        }

        //设置画笔
        Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        //字体大小
        textPaint.setTextSize(200f);
        //采用默认的宽度
        textPaint.setTypeface(Typeface.DEFAULT);
        //采用的颜色
        textPaint.setColor(Color.BLACK);

        // 时间水印
        String mark = formateDate("yyyy.MM.dd HH:mm:ss");
        float textWidth = textPaint.measureText(mark);
        canvas.drawText(mark, bitmap.getWidth() - textWidth - 10, bitmap.getHeight() - 26, textPaint);
        return bitmap;
    }

    /**
     * 圆角
     * Created by 飘凌雪 on 2017/2/23.
     */

    public static String formateDate(String pattern) {
        String nowtime = null;
        SimpleDateFormat ch = null;
        try {
            ch = new SimpleDateFormat(pattern,
                    Locale.CHINESE);

            nowtime = ch.format(new Date());
            return nowtime;
        } catch (Exception e) {
            e.printStackTrace();
            ch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                    Locale.CHINESE);

            nowtime = ch.format(new Date());
            return nowtime;
        }

    }

    public enum ImageCorner {
        LEFT_TOP,//左上角
        LEFT_BOTTOM,//左下角
        RIGHT_TOP,//右上角
        RIGHT_BOTTOM//右下角
    }
}
